package com.itheima.controller;

import com.aliyuncs.exceptions.ClientException;
import com.itheima.constant.MessageConstant;
import com.itheima.constant.RedisMessageConstant;
import com.itheima.entity.Result;
import com.itheima.utils.SMSUtils;
import com.itheima.utils.ValidateCodeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

/**
 * 验证码
 */
@RestController
@RequestMapping("/validateCode")
public class ValidateCodeController {

    @Autowired
    private JedisPool jedisPool;

    /**
     * 发送预约验证码
     * @param telephone  手机号
     * @return  true or false
     */
    @RequestMapping("/send4Order")
    public Result send4Order(String telephone) {
        //生成随机验证码
        String validateCode = ValidateCodeUtils.generateValidateCode(4).toString();

        try {
            //发送短信      ,"15172329493","1234"
            SMSUtils.sendShortMessage(SMSUtils.VALIDATE_CODE, telephone, validateCode);
        } catch (ClientException e) {
            e.printStackTrace();
            //发送失败
            return new Result(false, MessageConstant.SEND_VALIDATECODE_FAIL);
        }

        //将验证码保存到redis中(5分钟)                                                                   todo 有效时间延长 ,后期更改300秒
        jedisPool.getResource().setex(telephone + RedisMessageConstant.SENDTYPE_ORDER, 2 * 60 * 60 * 12 * 5, validateCode);

        //发送成功
        return new Result(true, MessageConstant.SEND_VALIDATECODE_SUCCESS);
    }


    //发送登录验证码
    @RequestMapping("/send4Login")
    public Result send4Login(String telephone) {
        //生成随机验证码
        String validateCode = ValidateCodeUtils.generateValidateCode(4).toString();

        try {
            //发送短信      ,"15172329493","1234"
            SMSUtils.sendShortMessage(SMSUtils.VALIDATE_CODE, telephone, validateCode);
        } catch (ClientException e) {
            e.printStackTrace();
            //发送失败
            return new Result(false, MessageConstant.SEND_VALIDATECODE_FAIL);
        }


        //将验证码保存到redis中(5分钟)                                                                   todo 有效时间延长 ,后期更改300秒
        jedisPool.getResource().setex(telephone + RedisMessageConstant.SENDTYPE_LOGIN, 2 * 60 * 60 * 12 * 5, validateCode);

        //发送成功
        return new Result(true, MessageConstant.SEND_VALIDATECODE_SUCCESS);
    }


}
